﻿using MasterNode.Interfaces;
using Quartz.Spi;
using Quartz.Simpl;
using System.Threading;
using Quartz;
using MapReduceLib.DataModel;
using MapReduceLib.Contracts;
using System.ServiceModel;
using System.Collections.Generic;

namespace MasterNode.ServiceImpl
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults = true)]
    class TaskTracker : ITaskTracker
    {
        private IJobRepository jobRepository;
        private IThreadPool threadPool;
        private List<ThreadRanJob> runningJobs;

        public TaskTracker(IJobRepository jobRepository)
        {
            this.jobRepository = jobRepository;
            threadPool = new SimpleThreadPool(10, ThreadPriority.Normal); // TODO make config item out of it
            threadPool.Initialize();
            runningJobs = new List<ThreadRanJob>();
        }

        #region ITaskExecuter Members

        public bool RunJob(string jobId)
        {
            return RunJob(jobId, new Dictionary<string, string>());
        }

        public bool RunJob(string jobId, Dictionary<string, string> parameters)
        {
            Job job = jobRepository.GetJob(jobId);
            ThreadRanJob runningJob = new ThreadRanJob(job);

            bool started = threadPool.RunInThread(runningJob);
            if (started)
            {
                runningJobs.Add(runningJob);
            }

            return started;
        }

        #endregion

        class ThreadRanJob : IThreadRunnable
        {
            private Job job;

            public ThreadRanJob(Job job)
            {
                this.job = job;
            }

            public void Run()
            {
                //.....
            }
        }
    }
}
